package com.test.personalblogproject.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.test.personalblogproject.mapper.UserMapper;
import com.test.personalblogproject.pojo.Result;
import com.test.personalblogproject.pojo.User;
import com.test.personalblogproject.service.UserService;
import com.test.personalblogproject.utils.MailUtil;
import com.test.personalblogproject.utils.Md5Util;
import com.test.personalblogproject.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.MailSender;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MailSender mailSender;



    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public void register(String username, String password) {
        //加密
        String md5String = Md5Util.getMD5String(password);
        //添加
        userMapper.add(username,md5String);
    }
   // private static final ThreadLocal THREAD_LOCAL = new ThreadLocal();
    @Override
    public void updatePwd(String newPwd) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        String md5String = Md5Util.getMD5String(newPwd);
        userMapper.updatePwd(md5String,id);
    }

    @Override
    public void logout(String  token) {
        redisTemplate.delete(token);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);
        ThreadLocalUtil.remove();
    }
    @Override
    public void updateNike(User user) {
        String nickname = user.getNickname();
        Integer id = user.getId();
        userMapper.updateNike(id,nickname);
    }
    @Override
    public void updateEmail(User user) {
        String email = user.getEmail();
        Integer id = user.getId();
        userMapper.updateEmail(id,email);
    }
    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl,id);
    }
    @Override
    public Result sendByemail(String email) {
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("email",email);
        List<User>list=userMapper.selectByMap(hashMap);
        if(list.isEmpty()) return Result.error("邮箱不存在");

        String token = JWT.create()
                .withClaim("email", email)
                .withClaim("type", "resetPwd")
                .withExpiresAt(new Date(System.currentTimeMillis() +  1000*30 * 60 ))//token有效期30min
                .sign(Algorithm.HMAC256("personal-blog-project"));

        MailUtil.sendResetMail(mailSender, email, token);
        return Result.success("重置邮件已发送，请查收");


    }
    @Override
    public Result resetPwdByToken(String token, String newPwd) {
        try {
            DecodedJWT jwt = JWT.require(Algorithm.HMAC256("personal-blog-project"))
                    .build()
                    .verify(token);

            // 校验类型
            if (!"resetPwd".equals(jwt.getClaim("type").asString())) {
                return Result.error("非法 token");
            }

            String email = jwt.getClaim("email").asString();


            String md5String = Md5Util.getMD5String(newPwd);
            userMapper.resetPwdByemail(email,md5String);

            return Result.success("密码已重置，请重新登录");
        } catch (JWTVerificationException e) {
            return Result.error("链接已失效或已过期");
        }


    }
    @Override
    public User findByUserId(int id) {
        return userMapper.findById(id);
    }
}
